package com.mazaiting.accessibilityservicetest;

import android.accessibilityservice.AccessibilityService;
import android.os.Build;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;

/**
 * 控制无障碍服务
 * Created by mazaiting on 2017/8/18.
 */
public class AccessibilityOperator {
  private static final String TAG = "AccessibilityOperator";
  private static AccessibilityOperator mInstance;
  
  private AccessibilityOperator() {
  }
  
  public static AccessibilityOperator getInstance() {
    if (mInstance == null) {
      synchronized (AccessibilityOperator.class) {
        if (mInstance == null) {
          mInstance = new AccessibilityOperator();
        }
      }
    }
    return mInstance;
  }
  
  private AccessibilityService mAccessibilityService;
  private AccessibilityEvent mAccessibilityEvent;
  
  /**
   * 更新事件
   *
   * @param service
   * @param event
   */
  public void updateEvent(AccessibilityService service, AccessibilityEvent event) {
    if (mAccessibilityService == null && service != null) {
      mAccessibilityService = service;
    }
    if (event != null) {
      mAccessibilityEvent = event;
    }
  }
  
  /**
   * 根据Text搜索所有符合条件的节点，模糊搜索方式
   *
   * @param text
   * @return
   */
  public boolean clickText(String text) {
    AccessibilityNodeInfo nodeInfo = getRootNodeInfo();
    if (nodeInfo != null) {
      List<AccessibilityNodeInfo> nodeInfos =
              nodeInfo.findAccessibilityNodeInfosByText(text);
      return performClick(nodeInfos);
    }
    return false;
  }
  
  /**
   * 获取根节点
   *
   * @return
   */
  private AccessibilityNodeInfo getRootNodeInfo() {
    Log.e(TAG, "getRootNodeInfo: ");
    AccessibilityEvent curEvent = mAccessibilityEvent;
    AccessibilityNodeInfo nodeInfo = null;
    if (mAccessibilityService != null) {
      // 获得窗体根节点
      nodeInfo = mAccessibilityService.getRootInActiveWindow();
    }
    return nodeInfo;
  }
  
  /**
   * 模拟点击
   *
   * @param nodeInfos
   * @return true 成功； false 失败。
   */
  private boolean performClick(List<AccessibilityNodeInfo> nodeInfos) {
    if (nodeInfos != null && !nodeInfos.isEmpty()) {// 判断是否非空
      AccessibilityNodeInfo nodeInfo;
      for (int i = 0; i < nodeInfos.size(); i++) {
        nodeInfo = nodeInfos.get(i);// 获得要点击的View
        // 进行模拟点击
        if (nodeInfo.isEnabled()) {// 如果可以点击
          return nodeInfo.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        }
      }
    }
    return false;
  }
}